package org.jflame.captcha;

import org.jflame.captcha.cache.CaptchaCache;
import org.jflame.captcha.creator.CaptchaCreator;
import org.jflame.captcha.creator.factory.CaptchaCreatorFactory;
import org.jflame.captcha.validator.Verifiable;
import org.jflame.commons.config.ConfigReader;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("rawtypes")
public class CaptchaService {

    private Map<String,CaptchaCreator> creatorMap = new HashMap<>();
    private CaptchaCache captchaCache;

    public CaptchaService(ConfigReader cfg, CaptchaCache _captchaCache) {
        String[] typeNames = cfg.getStringArray(CaptchaCreatorFactory.KEY_TYPE);
        for (String type : typeNames) {
            creatorMap.put(type, CaptchaCreatorFactory.build(type, cfg));
        }
    }

    /**
     * 创建验证码,并使用传入的id缓存验证码可验证数据
     * 
     * @param id
     * @return
     */
    public Captcha create(String captchaType, String id) {
        CaptchaCreator creator = creatorMap.get(captchaType);
        if (creator == null) {
            throw new RuntimeException("未配置" + captchaType + "类型验证码创建器");
        }
        Captcha captcha = creator.create();
        captchaCache.put(id, captcha.getVerifiable());
        return captcha;
    }

    /**
     * 校验验证码是否正确
     * 
     * @param id 正确的验证码id
     * @param inputVerifiable 待检验的验证属性
     * @return
     */
    @SuppressWarnings("unchecked")
    public boolean verify(String id, Verifiable inputVerifiable) {
        Verifiable v = captchaCache.get(id);
        if (v == null) {
            return false;
        }
        boolean isOk = v.verify(inputVerifiable);
        captchaCache.evict(id);
        return isOk;
    }

    public Verifiable parse(String captchaType, String verifiableString) {
        CaptchaCreator creator = creatorMap.get(captchaType);
        if (creator != null) {
            return creator.parse(verifiableString);
        }
        throw new IllegalArgumentException(captchaType + " is not supported captchaType");
    }
}
